import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Node from '@design/core/components/Node';
import Value from '@design/core/model/value';
import { findNode, getKey } from '@design/core/utils/find-node';
import { DropDecorator } from '../decorator';
import 'Devices.css/assets/devices.min.css';
import './Content.less';

@DropDecorator()
class Content extends PureComponent {
  static propTypes = {
    value: PropTypes.instanceOf(Value).isRequired,
    editor: PropTypes.object.isRequired,
  };

  handleClick = event => {
    const { value, editor } = this.props;
    const selectedNode = value.selection.first();
    if (selectedNode && selectedNode.key === getKey(event.target)) {
      return;
    }
    let node = findNode(event.target, value);
    if (node) {
      node = editor.getNotAtomicNode(node);
      editor.setSelection([node]);
    } else {
      editor.setSelection([]);
    }
  };

  renderNode = node => {
    const { value } = this.props;
    const { selection } = value;
    const isSelected = value.isSelected(node);
    let selectedPath;
    if (selection.first()) {
      selectedPath = node.getPath(selection.first().key);
    }
    return (
      <Node
        selectedPath={selectedPath}
        isSelected={isSelected}
        key={node.key}
        node={node}
        parent={this.props.value.document}
        editor={this.props.editor}
        value={value}
      />
    );
  };

  onEdit = () => {
    const { editor, node } = this.props;
    if (editor.showPropertyEditor) {
      editor.showPropertyEditor(node);
    }
  };

  render() {
    const { value, connectDropTarget } = this.props;
    const { document } = value;
    const children = document.nodes.toArray().map(this.renderNode);
    const attributes = { 'data-key': document.key };
    const content = connectDropTarget(
      <div
        {...attributes}
        style={document.style.toJS()}
        className="mobile-form"
        onClick={this.handleClick}
      >
        {children}
        {this.props.children}
      </div>
    );
    return (
      <div className="device marvel-device note8">
        <div className="inner" />
        <div className="overflow">
          <div className="shadow" />
        </div>
        <div className="speaker" />
        <div className="sensors" />
        <div className="camera" />
        <div className="screen">
          <div className="status-bar">表单设计器</div>
          {content}
        </div>
      </div>
    );
  }
}

export default Content;
